class MonthPay extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            orderId: getUrlParam("orderId"),
            code: getUrlParam("code")
        };
    }

    onBridgeReady(){
        postJson("/api/v2/pay/anon/weixin/H5/order", {
            orderId: this.state.orderId,
            code: this.state.code
        }, (data) => {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', data,
                (res) => {
                    WeixinJSBridge.call('closeWindow');
                }
            );
        }, (data) => {
            Toast.info(data.data ? data.data : data, 2, null, false);
        })
    }

    componentDidMount() {
        let userAgent = window.navigator.userAgent.toLowerCase();
        let weixinpay = userAgent.match(/MicroMessenger/i);
        if (weixinpay) {
            if (typeof WeixinJSBridge === "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', () => this.onBridgeReady(), false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', () => this.onBridgeReady());
                    document.attachEvent('onWeixinJSBridgeReady', () => this.onBridgeReady());
                }
            } else {
                this.onBridgeReady();
            }
        } else {
            this.refs.subButton.click();
        }

    }

    render() {
        return (
            <form action="/api/v2/pay/anon/alipay/H5/order">
                <input type="hidden" name="orderId" value={this.state.orderId}/>
                <div style={{
                    width: '100%',
                    position: 'fixed',
                    bottom: 0,
                    display: 'none'
                }}>
                    <button type="submit" ref="subButton" style={{width: '100%'}}>
                        确定支付
                    </button>
                </div>
            </form>
        );
    }
}

ReactDOM.render(
    (<MonthPay/>),
    document.getElementById('root')
);